import {defineStore} from "pinia";
import {CreateSocket} from "../util/websocket";
import {ref} from "vue";
import {wsData} from "../type/websocket";
import {sendMessage} from "../type/websocket";
import {useFriendStore} from "./friend";
import dayjs from "dayjs";

// 聊天的仓库

export const useChatStore = defineStore('chat', () => {
    // 储存socket
    let socket = ref<WebSocket>()

    // 启用ws
    function CreateWS(): Promise<WebSocket | undefined> {
        return new Promise((resolve, reject) => {
            socket.value = CreateSocket()

            if (socket.value?.readyState == 0) {
                socket.value?.addEventListener("open", () => {
                    resolve(socket.value)
                })
            } else {
                resolve(socket.value)
            }

        })
    }

    // 发送消息
    async function SendWS(data: string) {
        await CreateWS()
        socket.value?.send(data)
    }

    // 发送聊天数据
    async function SendMessage(data: wsData<sendMessage>) {
        // 发送消息
        await SendWS(JSON.stringify(data))

        // 将聊天数据追加到当前聊天会话中
        const friendStore = useFriendStore()
        friendStore.pushFriendChat({
            date_time: dayjs().format(),
            // 0就可以代表自己了
            id: 0,
            msg: data.data.message,
            read: true
        })
    }

    return {
        SendMessage
    }
})